import json
import traceback

import tornado.web

from logger_config import logger


class HttpBasicHandler(tornado.web.RequestHandler):
    def set_default_headers(self):
        # 无论是否跨域，都预设如下response_header，在调试或者线上均可用
        self.set_header("Access-Control-Expose-Headers", "Content-Disposition")
        self.set_header("Access-Control-Allow-Origin", self.request.headers.get('Origin') or "*")
        self.set_header('Access-Control-Allow-Credentials', "true")
        self.set_header('Access-Control-Allow-Methods', 'PUT,DELETE,OPTIONS,GET,POST')
        self.set_header("Content-Type", "application/json; charset=utf-8")

    def get_remote_ip(self):
        return self.request.headers.get("X-Real-IP") or \
            self.request.headers.get("X-Forwarded-For") or \
            self.request.remote_ip

    @property
    def data(self):
        # 获取url 和 body中的参数
        argument_data = dict()
        a = self.request.query_arguments
        for i in a.keys():
            argument_data[i] = self.get_argument(i)
        if self.request.body:
            body_data = json.loads(self.request.body.decode('utf-8'))
            if isinstance(body_data, dict):
                body_data.update(argument_data)
                return body_data
            else:
                logger.exception('body data is not a dict')
        else:
            return argument_data

    def _set_response_data(self, result):
        try:
            self.finish(json.dumps(result, ensure_ascii=False))
        except Exception as e:
            self.finish(json.dumps(
                {"code": 'fail', "info": str(e)}))
            traceback.print_exc()

    def send_response_data(self, code, data=None, info=None):
        result = dict()
        result['code'] = code
        result['info'] = info
        result['data'] = data
        self._set_response_data(result)
